<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use App\Model\{Config,Cash,User};

class queue extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'songshu:queue';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '队列任务';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        while(true){
            $data =  Redis::lpop('songshu:queue');
            if($data!=null){
                $data = json_decode($data,true);
                $function = 'exec'.$data['work_type'];
                $this->$function($data['data']);
                $this->log('songshu:queue',$data['work_type'],$data);
                DB::disconnect('mysql');
            }else{
                usleep(10000);
            }
        }
    }
    public function log($key,$work_type,$data){
        if($work_type!=6) {
            DB::table('songsu_queue_log')->insert([
                'key'=>$key,
                'work_type'=>$work_type,
                'json'=>json_encode($data),
                'add_time'=>time()
            ]);
        }
    }
    /**
     * 积分队列任务
     * 在yii框架实现，弃用
     * @return [type] [description]
     */
    public function exec1($data){
        return '';
        if( !DB::table('integral')->where('uid',$data['uid'])->exists() ){
            if( !DB::table('integral')->insert(['uid'=>$data['uid']]) ){
                return false;
            }
        }
        DB::beginTransaction();
        $info = DB::table('integral')->where('uid',$data['uid'])->lockForUpdate()->first(['balance']);
        $current = $info->balance+$data['integral'];
        $step1 = DB::table('integral_task')->where('id',$data['id'])->update(['status'=>1]);
        $step2 = DB::table('integral_log')->insert([
            'uid'=>$data['uid'],
            'affect'=>$data['integral'],
            'type'=>1,
            'current'=>$current,
            'add_time'=>$data['add_time'],
            'td_id'=>$data['td_id'],
            'ts_id'=>$data['ts_id']
        ]);
        $step3 = DB::table('integral')->where('uid',$data['uid'])->update([
            'history'=>DB::raw("`history`+".$data['integral']),
            'balance'=>DB::raw("`balance`+".$data['integral']),
        ]);
        if( $step1!==false && $step2!==false && $step3!==false ){
            DB::commit();
            return true;
        }else{
            DB::rollBack();
            return false;
        }
    }

    /**
     * 普通用户提现队列
     */
    public function exec2($data){
        $info = DB::table('txdata')->where('id',$data['id'])->first(['payment_type']);
        if($info->payment_type==1){
            $rs = (new Cash())->tx($data['id']);
            dump($rs);
        }elseif($info->payment_type==2){
            $rs = (new Cash())->tx_alipay($data['id']);
            dump($rs);
        }
        #$rs = (new Cash())->tx($id);
        #echo $data['id']."\n";
        #sleep(3);
    }

    /**
     * 合伙人提现队列
     */
    public function exec3($data){
        $info = DB::table('partner_cash')->where('id',$data['id'])->first(['payment_id']);
        if($info->payment_id==1){
            $rs = (new Cash())->wx_pay($data['id']);
            dump($rs);
        }elseif($info->payment_id==2){
            $rs = (new Cash())->partner_pay($data['id']);
            dump($rs);
        }
    }

    /**
     * 封禁 解封
     */
    public function exec4($data){
        if($data['type']==1){
            $s1 = DB::table('txdata')->where('uid',$data['id'])->where('state','<>',1)->update(['user_status'=>0]);
            $s2 = DB::table('partner_cash')->where('uid',$data['id'])->where('pay_status',0)->update(['user_status'=>0]);
        }elseif($data['type']==2){
            $s1 = DB::table('txdata')->where('uid',$data['id'])->where('state','<>',1)->update(['user_status'=>1]);
            $s2 =  DB::table('partner_cash')->where('uid',$data['id'])->where('pay_status',0)->update(['user_status'=>1]);
        }
        dump($s1,$s2);
    }

    /**
     * 直升合伙人异步
     * $data = [
     *    order_no,
     *    sf_id,
     *    sz_id
     * ];
     */
    public function exec5($data){
        $order = DB::table('order')->where('order_no',$data['order_no'])->where('pay_status',1)->first(['id','uid','pay_status','add_time','pay_time']);
        if(empty($order)){
            return false;
        }
        #升级合伙人
        $uid = $order->uid;
        (new User)->separate_tree($uid);
        
        #积分
        $affect = 200;
        if( !DB::table('integral')->where('uid',$uid)->exists() ){
            DB::table('integral')->insert([
                'uid'=>$uid
            ]);
        }

    
        DB::beginTransaction();
        $integral = DB::table('integral')->where('uid',$uid)->lockForUpdate()->first();
        $insert_log = DB::table('integral_log')->insert([
            'uid'=>$uid,
            'affect'=>$affect,
            'type'=>2,
            'current'=>$integral->balance+$affect,
            'add_time'=>time(),
        ]);
        $update_integral = DB::table('integral')->where('uid',$uid)->update([
            'balance'=>DB::raw("`balance`+".$affect),
            'history'=>DB::raw("`history`+".$affect),
        ]);
        if($insert_log && $update_integral){
            DB::commit();
        }else{
            DB::rollBack();
        }

        #推送
        DB::table('message')->insert([
            'uid'=>$uid,
            'is_system'=>0,
            'type'=>3,
            'title'=>'恭喜您升级为合伙人',
            'content'=>"恭喜您，在" . date('Y-m-d H:i') . "达到升级合伙人条件，我们现已将您的账户升级为合伙人！",
            'add_time'=>time(),
            'click_url'=>'songshu://songshutoutiao.com/native?url=partner_login&need_login=1',
            'button_name'=>'去查看',
            'show_type'=>3,
        ]);

        $array = array(
            'work_type' => "4",
            'title' => "恭喜您升级为超级会员",
            'text' => "恭喜您，在" . date('Y-m-d H:i') . "达到升级超级会员条件，我们现已将您的账户升级为超级会员！",
            'reg_id' => $uid,
            'list' => array(
                'work_type' => "4",
                'type' => "2",//1升级为超级会员  2升级为合伙人
                'click_url' => 'songshu://songshutoutiao.com/native?url=partner_login&need_login=1'
            )
        );
        $array = json_encode($array);
        Redis::rpush('queue:jpush', $array);
    }

    /**
     * 增加用户资金日志表
     * @param  [type] $data [description]
     * @return [type]       [description]
     */
    public function exec6($data)
    {
        dump($data);
        $uid = $data['uid'];
        $ref_handle_id = $data['ref_handle_id'];
        $info = DB::table('ref_handle')->where([
            ['id','=',$ref_handle_id],
            ['ref_u_id','=',$data['ref_u_id']],
            ['ref_m_id','=',$data['ref_m_id']],
            ['uid','=',$data['uid']],
        ])->exists();
        if(!$info)
        {
            echo "not exists\n";
            return true;
        }

        $suffix = substr($uid, -2);
        if($suffix<10) {
            $suffix = str_pad($suffix, 2, "0", STR_PAD_LEFT);
        }

        $table = 'refererdata_'.$suffix;
        DB::beginTransaction();
        $insert = DB::connection('db3')->table($table)->insert([
            'uid'=>$uid,
            'ref_u_id'=>$data['ref_u_id'],
            'ref_m_id'=>$data['ref_m_id'],
            'td_id'=>$data['td_id'],
            'ts_id'=>$data['ts_id'],
            'income_type'=>$data['income_type'],
            'task_id'=>$data['task_id'],
            'coin'=>$data['coin'],
            'rate'=>$data['rate'],
            'money'=>$data['money'],
            'use_gifts_id'=>$data['use_gifts_id'],
            'added_coin'=>$data['added_coin'],
            'identifying'=>$data['identifying'],
            'type'=>$data['type'],
            'time'=>$data['time'],
            'ymd'=>$data['ymd'],
        ]);
        $update = DB::table('ref_handle')->where('id',$ref_handle_id)->update(['ref_status'=>1]);
        if($insert!==false && $update!==false)
        {
            DB::commit();
            echo $table."\n";
            return true;
        }
        DB::rollBack();
        echo "rollBack"."\n";
    }

    /**
     * 升级合伙人 修改团队人数
     */
    public function exec7($data)
    {
        $affect = DB::table('user_tree')->whereIn('uid',$data)->update([
            'all_count'=>DB::raw("(`right`-`left`-1)/2")
        ]);
        #echo $affect."\n";
    }
}
